package com.gqj.soapclient;

import okhttp3.*;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class client {
    //出入库明细上传接口
    public static int sibSendIOInfo(String operId)throws IOException, ParserConfigurationException, SAXException {
        // 创建OkHttp客户端
        OkHttpClient client = new OkHttpClient();

        // 请求的XML内容，注意替换为你实际的请求内容
        String requestXml = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://webservice.isvm.hzwq.com\">\n" +
                "   <soapenv:Header/>\n" +
                "   <soapenv:Body>\n" +
                "      <ser:sibSendIOInfo>\n" +
                "         <!--Optional:-->\n" +
                "         <in0>%s</in0>\n" + // 这里的%s是占位符，会被下面的String.format()方法动态替换为in0Value的值
                "      </ser:sibSendIOInfo>\n" +
                "   </soapenv:Body>\n" +
                "</soapenv:Envelope>";
        requestXml = String.format(requestXml, operId);

        // 构建请求体，指定SOAPAction
        RequestBody requestBody = RequestBody.create(MediaType.parse("text/xml;charset=utf-8"), requestXml);
        Request request = new Request.Builder()
                .url("http://10.234.15.156:17021/sibService/sibBusiness/services/WHWebService")
                .post(requestBody)
                .addHeader("SOAPAction", "")
                .build();

        // 发送请求
        Response response = client.newCall(request).execute();
        String responseBody = response.body().string();

        // 解析返回值
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(new ByteArrayInputStream(responseBody.getBytes(StandardCharsets.UTF_8)));
        document.getDocumentElement().normalize();
        String result = document.getElementsByTagName("ns1:out").item(0).getTextContent();

        Map<String, String> resultMap = parseResult(result);
        System.out.println(resultMap);
        return 0;
    }

    //出入库任务完成接口
    public static int sibUpIOResult(String ioTaskNo, String taskStatus)throws IOException, ParserConfigurationException, SAXException {
        // 创建OkHttp客户端
        OkHttpClient client = new OkHttpClient();

        // 构造XML字符串
        String paraXml = String.format("<PARA><IO_TASK_NO>%s</IO_TASK_NO><TASK_STATUS>%s</TASK_STATUS></PARA>", ioTaskNo, taskStatus);
        String in0Value = String.format("<![CDATA[%s]]>", paraXml);
        String requestXml = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://webservice.isvm.hzwq.com\">\n" +
                "   <soapenv:Header/>\n" +
                "   <soapenv:Body>\n" +
                "      <web:sibUpIOResult>\n" +
                "         <web:in0>%s</web:in0>\n" +
                "      </web:sibUpIOResult>\n" +
                "   </soapenv:Body>\n" +
                "</soapenv:Envelope>";
        requestXml = String.format(requestXml, in0Value);
        System.out.println("入参：" + requestXml);

        // 构建请求体，指定SOAPAction
        RequestBody requestBody = RequestBody.create(MediaType.parse("text/xml;charset=utf-8"), requestXml);
        Request request = new Request.Builder()
                .url("http://10.234.15.156:17021/sibService/sibBusiness/services/WHWebService")
                .post(requestBody)
                .addHeader("SOAPAction", "")
                .build();

        // 发送请求
        Response response = client.newCall(request).execute();
        String responseBody = response.body().string();

        // 解析返回值
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(new ByteArrayInputStream(responseBody.getBytes(StandardCharsets.UTF_8)));
        document.getDocumentElement().normalize();
        String result = document.getElementsByTagName("ns1:out").item(0).getTextContent();

        Map<String, String> resultMap = parseResult(result);
        System.out.println(resultMap);
        return 0;
    }

    public static Map<String, String> parseResult(String result) {
        Map<String, String> resultMap = new HashMap<>();
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            InputSource is = new InputSource(new StringReader(result));
            Document doc = builder.parse(is);
            NodeList nodes = doc.getElementsByTagName("RESULT_FLAG");
            if (nodes != null && nodes.getLength() > 0) {
                String resultFlag = nodes.item(0).getTextContent();
                resultMap.put("RESULT_FLAG", resultFlag);
            }
            nodes = doc.getElementsByTagName("ERROR_INFO");
            if (nodes != null && nodes.getLength() > 0) {
                String errorInfo = nodes.item(0).getTextContent();
                resultMap.put("ERROR_INFO", errorInfo);
            }
        } catch (ParserConfigurationException | SAXException | IOException e) {
            e.printStackTrace();
        }
        return resultMap;
    }
}
